<?php

namespace ShowStop\UserBundle\Controller;

use Symfony\Component\HttpFoundation\Response;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use ShowStop\UserBundle\Entity\User;
use ShowStop\UserBundle\Entity\Role;
use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\Validator\Constraints\MinLength;
use Symfony\Component\Validator\Constraints\MaxLength;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;

// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class UserController extends Controller
{
	/**
	* @Route("/users", name="_showstop_users")
	* @Template()
	*/
    public function usersAction()
    {
    	//get doctrine entity manager
    	$em = $this->getDoctrine()->getEntityManager();
    	
    	$query = $em->createQuery( 'SELECT u FROM ShowStopUserBundle:User u' );
    	
    	$users = $query->getResult();
    	
    	if (!$users) {
    		throw $this->createNotFoundException( "No users found");
    	}
    	
        return $this->render('ShowStopUserBundle:User:users.html.twig', array('users' => $users));
    }
    
    /**
    * @Route("/user/profile", name="_profile")
    * @Template()
    */
    public function profileAction(Request $request) {
    	
    	$user = $this->get('security.context')->getToken()->getUser();
    	
    	//make sure the user is logged in
    	if(!$user)
    		return $this->redirect($this->generateUrl('_login'));
    	
    	//array of years to be used in birthyear drop down
    	$years 	= array();
    	for( $i = (int)date("Y"); $i >= 1900 ; $years[] = $i, $i--  );
    	
    	$form = $this->createFormBuilder($user)
				->add('fname', 'text')
    			->add('lname', 'text')
    			->add('username', 'text')
    			->add('email', 'text')
    			->add('gender', 'choice', 
    				   array('choices' => array('m' => 'Male', 'f' => 'Female'), 'expanded' => true))
    			->add('birth', 'choice', array('choices' => $years ))
    			->getForm();
    	 
    	if ($request->getMethod() == 'POST') {
    		
			$form->bindRequest($request);
    		 
	    	if ($form->isValid()) {
    			 
	    		//persist updated user to db
    			$em = $this->getDoctrine()->getEntityManager();
    			$em->persist($user);
    			$em->flush();
    			
	    		return $this->redirect($this->generateUrl('_profile_success'));
    		}
    		
    	}
    	
    	return $this->render('ShowStopUserBundle:User:profile.html.twig', array('form' => $form->createView() ) );
    }
    
    /**
     * @Route("/user/profileSuccess", name="_profile_success")
     * @Template()
     */
    public function profileSuccessAction() {
    	
    	return $this->render('ShowStopUserBundle:User:profileSuccess.html.twig', array() );
    }
    
    /**
     * @Route("/user/password", name="_password")
     * @Template()
     */
    public function passwordAction(Request $request) {
    	
    	$user = $this->get('security.context')->getToken()->getUser();
    	
    	//make sure the user is logged in
    	if(!$user)
    		return $this->redirect($this->generateUrl('_login'));
    	
    	$form = $this->createFormBuilder( null )
    		    ->add('oldPassword', 'password')
    		    ->add('newPassword', 'password')
    		    ->add('confirmNewPassword', 'password')
    		    ->getForm();

    	if ( $request->getMethod() == 'POST' ) {
    			
			$form->bindRequest($request);
    			
    		if ($form->isValid()) {
    			// get the current encoder for this user provider
    			$factory = $this->get('security.encoder_factory');
    			$encoder = $factory->getEncoder($user);
    		
    			$data = $form->getData();
				
    			//check current hashed password in user session to one entered on page
    			if( $user->getPassword() == $encoder->encodePassword( $data['oldPassword'], $user->getSalt() ) ) {
    				
    				//encrypt password with currently configured encoder
    				$password = $encoder->encodePassword( $data['newPassword'], $user->getSalt() );
    				$user->setPassword( $password );
    				
    				//persist updated password in db
    				$em = $this->getDoctrine()->getEntityManager();
    				$em->persist($user);
    				$em->flush();
    			
    				return $this->redirect($this->generateUrl('_password_success'));

    			} else {
    				
    				$form = $this->createFormBuilder( $msg )
							->add('oldPassword', 'password')
    						->add('newPassword', 'password')
    						->add('confirmNewPassword', 'password')
    						->getForm();

    			}
    		}
    	}
    	
    	return $this->render('ShowStopUserBundle:User:password.html.twig', array('form' => $form->createView() ) );
    }
    
    /**
    * @Route("/user/passwordSuccess", name="_password_success")
    * @Template()
    */
    public function passwordSuccessAction(Request $request) {
    	
    	return $this->render('ShowStopUserBundle:User:passwordSuccess.html.twig', array() );
    }
    
    /**
    * @Route("/register", name="_register")
    * @Template()
    */
    public function registerAction(Request $request) {
    	
    	$user 	= new User();
    	
    	//array of years to be used in birthyear drop down
    	$years 	= array();
    	for( $i = (int)date("Y"); $i >= 1900 ; $years[] = $i, $i--  );
    	
    	$form = $this->createFormBuilder($user)
	    	->add('fname', 'text')
	    	->add('lname', 'text')
	    	->add('username', 'text')
	    	->add('password', 'password')
	    	->add('email', 'text')
	    	->add('gender', 'choice', array(
	    	    'choices'   => array('m' => 'Male ', 'f' => 'Female '),
	    	    'expanded'	=> true
	    	))
	    	->add('birth', 'choice', array(
    			'choices' => $years ) )
	    	->getForm();
    	
    	if ($request->getMethod() == 'POST') {
    		$form->bindRequest($request);
    	
    		if ($form->isValid()) {    			
    			$em = $this->getDoctrine()->getEntityManager();
    			
    			//select default role for new user registrations: ROLE_USER
    			$query = $em->createQuery( "SELECT r FROM ShowStopUserBundle:Role r WHERE r.name = 'ROLE_USER'" );
    			$role = $query->getResult();
    			
    			//create new salt based on current time
    			$user->setSalt( md5( time() ) );
    			
    			// get the current encoder for this user provider
    			$factory = $this->get('security.encoder_factory');
    			$encoder = $factory->getEncoder($user);

    			//encrypt password with currently configured encoder
    			$password = $encoder->encodePassword( $user->getPassword(), $user->getSalt() );
    			$user->setPassword( $password );
    			
    			//add new role to user
    			$user->getUserRoles()->add( $role[0] );
    			
    			//commit to db
    			$em->persist( $user );
    			$em->flush();
    	
    			return $this->redirect( $this->generateUrl('_register_success') );
    		} 
    	}
    	
    	return $this->render('ShowStopUserBundle:User:register.html.twig', array('form' => $form->createView() ) );
    }
    
    /**
    * @Route("/registerSuccess", name="_register_success")
    * @Template()
    */
    public function registerSuccessAction() {
    	 
    	return $this->render('ShowStopUserBundle:User:registerSuccess.html.twig', array() );
    }
    
    /**
     * @Route("/user/favorites", name="_favorites")
     * @Template()
     */
    public function favoritesAction() {
    	
    	$user = $this->get('security.context')->getToken()->getUser();
    	 
    	//make sure the user is logged in
    	if(!$user)
    		return $this->redirect($this->generateUrl('_login'));
    	
    	return $this->render( 'ShowStopUserBundle:User:favorites.html.twig', array( 'series' => $user->getUserFavorites() ) );
    }
    
    /**
     * @Route("user/favorites/add.{format}/{id}", requirements={"_format"="raw"}, name="_favorites_add")
     * @Template()
     */
    public function favoritesAddAction($id) {
    	
    	$user = $this->get('security.context')->getToken()->getUser();
    	 
    	//make sure the user is logged in
    	if(!$user)
    		return $this->redirect($this->generateUrl('_login'));
    	 
    	$em = $this->getDoctrine()->getEntityManager();
    	 
    	$query = $em->createQuery( "SELECT s FROM ShowStopTelevisionBundle:Series s WHERE s.id = " . $id );
    	$series = $query->getResult();

    	$messge = "failure";
    	if($series) {
    	
    		$user->getUserFavorites()->add( $series[0] );
    	 
	    	$em->persist( $user );
    		$em->flush();
    		
    		if($user->getUserFavorites()->contains( $series[0]))
    			$message = "success";
    	}
    	
    	return new Response($message);
    }
    
    /**
     * @Route("/user/favorites/remove.{format}/{id}", requirements={"_format"="raw"}, name="_favorites_remove")
     * @Template()
     */
    public function favoritesRemoveAction($id) {
    	 
    	$user = $this->get('security.context')->getToken()->getUser();
    
    	//make sure the user is logged in
    	if(!$user)
    		return $this->redirect($this->generateUrl('_login'));
    	
    	$em = $this->getDoctrine()->getEntityManager();
    	
    	$query = $em->createQuery( "SELECT s FROM ShowStopTelevisionBundle:Series s WHERE s.id = " . $id );
    	$series = $query->getResult();
    	
    	$message = "failure";
    	if($series && $user->getUserFavorites()->contains( $series[0] )) { 
    	
    		$user->getUserFavorites()->removeElement( $series[0] );
    	 
    		$em->persist( $user );
    		$em->flush();
    		
    		if(!$user->getUserFavorites()->contains( $series[0] ))
    			$message="success";    		
    	} 
    	
    	return new Response($message);
    }
    
}
